package org.example.likou150.searchTree;

import java.awt.desktop.AppReopenedEvent;

// https://leetcode.cn/problems/validate-binary-search-tree/?envType=study-plan-v2&envId=top-interview-150
// 总结：既然一个节点不合法直接返回结果不就行了？非想着把所有结果整合起来再返回？
public class IsValidBST {
    public static void main(String[] args) {
        IsValidBST isValidBST = new IsValidBST();

        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.right.left = new TreeNode(3);
        root.right.right = new TreeNode(6);
        isValidBST.isValidBST(root);
    }

    TreeNode preNode = null;
    public boolean isValidBST(TreeNode root) {
        if(root==null){
            return true;
        }

        if(!isValidBST(root.left)){
            return false;
        }

        if(preNode!=null){
            if(!(preNode.val < root.val)){
                return false;
            }
        }
        preNode = root;

       return isValidBST(root.right);
    }




    private static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
}
